<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" class="formInline" :rules="rules" ref="formInline" label-width="90px" slot="form" >          
                <el-row :gutter="41">
                    <el-col :span="8" class="myArea">
                        <el-form-item label="所属省">
                            <province v-model="formInline.fProvinceId"></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="myArea">
                        <el-form-item label="所属市">
                            <city v-model="formInline.fCityId" :province="formInline.fProvinceId"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="myArea">
                        <el-form-item label="所属区县">
                            <region v-model="formInline.fAreaId" :city="formInline.fCityId"></region>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="活动名称">
                            <el-input v-model="formInline.activityTitle" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="状态">
                            <el-select v-model="formInline.status" placeholder="请选择" style="width:100%">
                                <el-option v-for="item in formInline.statusList" :key="item.status" :label="item.statusName" :value="item.status">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="8">
                        <!-- <el-form-item label="创建人">
                            <el-select v-model="formInline.creator" filterable remote clearable reserve-keyword placeholder="请输入内容" :remote-method="remoteMethod" :loading="loading" style="width:100%">
                                <el-option v-for="item in formInline.creatorList" 
                                :key="item.pId" :label="item.sUserName" :value="item.pId">
                                </el-option>
                            </el-select>
                        </el-form-item> -->
                        <el-form-item label="创建人" prop="createrName">
                          <creator v-model="formInline.createrName" style="width:100%" @change='creatorChange'></creator>
                       </el-form-item>
                    </el-col>

                </el-row>
                <div class="top-line">
                    <el-button type="primary" @click="onSubmit('formInline')">查询</el-button>
                </div>

            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button @click="deleteRole">批量删除</el-button>
                    <el-button @click="goToaddActivity">添加</el-button>
                </div>
            </div>
            <el-table :data="dataApply" border style="width: 100%" @selection-change="handleSelectionChange" v-loading="loading">

                    <el-table-column label="全选" type="selection" :selectable="selectable"  width="55">
                    </el-table-column>

                    <el-table-column align="center" label="活动名称" prop="title" width="140">
                        <template scope="scope">
                            <span class="link-src btn" @click="goToactivityDetail(scope.row)">{{scope.row.title}}</span>
                        </template>
                    </el-table-column>
                    
                    <!--<el-table-column align="center" label="活动链接" prop="htmlUrl" show-overflow-tooltip></el-table-column>-->

                    <el-table-column align="center" label="创建人" prop="creatorName" width="120"></el-table-column>

                    <el-table-column align="center" label="创建时间" prop="createTime" width="170"></el-table-column>

                    <el-table-column align="center" label="上线时间" prop="onlineTime" width="170">
                        <template scope="scope">
                            {{scope.row.onlineTime == null ? '--' : scope.row.onlineTime}}
                        </template>
                    </el-table-column>

                    <el-table-column align="center" label="状态" prop="statusInfo"></el-table-column>

                    <el-table-column align="center" label="阅读数" prop="readNum"></el-table-column>

                    <el-table-column align="center" label="点赞数" prop="admireNum"></el-table-column>

                    <el-table-column align="center" label="点击次数" prop="clickNum"></el-table-column>

                    <el-table-column align="center" label="可见级别" prop="getLookStatus"></el-table-column>

                    <!--<el-table-column align="center" label="备注" prop="desc" show-overflow-tooltip>
                        <template scope="scope">
                            {{scope.row.desc == null ? '--' : scope.row.desc}}
                        </template>
                    </el-table-column>-->

                    <el-table-column label="操作" width="240">
                        <template scope="scope">
                            <!--<el-button class="btn btn-datail" @click="goToactivityDetail(scope.row)">查看</el-button>-->
                            <el-button v-if="scope.row.status=='1'" class="btn btn-outline" type="text" @click="onlineOrDown(scope.row)">下线</el-button>
                            <el-button v-if="scope.row.status=='0'" class="btn btn-online" type="text" @click="onlineOrDown(scope.row)">上线</el-button>
                            <el-button v-if="scope.row.status=='0'" class="btn btn-edit" type="text" @click="goToeditActivity(scope.row)">编辑</el-button>
                            <el-button v-if="scope.row.status=='0'" class="btn btn-del" type="text" @click="deleteList(scope.row)">删除</el-button>
                            <el-button v-if="scope.row.status=='0' && scope.row.htmlUrl" class="btn" type="text" @click="clipboardSuccessHandler(scope.row.htmlUrl)">复制链接</el-button> 
                        </template>
                    </el-table-column>                 
                </el-table>
                <div class="pagination-container" style="text-align:right">
                    <el-pagination
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="listQuery.total"
                        :current-page.sync="listQuery.page"
                        :page-sizes="config.pageSizes"
                        :page-size="config.pageSize"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
        </TableLayout>
    </div>
</template>

<script>
import {findActivityByPage, getDelete, onlineOrDown } from 'api/activityManagement';
import TableLayout from 'components/TableLayout';
import { mapState, mapActions } from 'vuex';
import { mapGetters } from 'vuex';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import creator from 'components/SchoolClasss/creator';
import Clipboard from 'v-clipboard';
export default{
    name: 'activityMangeList',
    components: {TableLayout, province, city, region, creator, Clipboard},
    data() {
        var validatehave=(rule, value, callback) => {
            if (this.formInline.creator||value=='') {
                callback();
            } else {
                callback(new Error('该创建人不存在'));
            }
        };
        return {
            choosed: true,
            formInline: {// form表单数据
                createrName: '', // 创建人的名字
                province: [], // 省列表
                findCity: [], // 市列表
                findArea: [], // 区列表
                creatorList: [], // 创建人列表
                fProvinceId: null, // 省
                fAreaId: null, // 市
                fCityId: null, // 区
                activityTitle: null, // 活动标题
                status: null, // 活动状态
                creator: null, // 创建人Id
                statusList: [// 状态列表
                    {
                        status: null,
                        statusName: '全部'
                    },
                    {
                        status: '1',
                        statusName: '上线'
                    },
                    {
                        status: '0',
                        statusName: '下线'
                    }
                ]
            },
            dataApply: [], // 回填数据
            multipleSelection: [],
            dialogFormVisible: false,
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            dialog: {
                dialogFormVisible: false,
                orgUserId: ''
            },
            loading: true,
            rules: {
                createrName: [
                    { validator: validatehave, trigger: 'blur,change' }
                ]
              
            }
        }
    },
    computed: {
        ...mapState({
            config: state => state.config.table,
            cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
        }),
    // 获取用户id
        ...mapGetters([
            'uid'
        ])
    },
    // 初始化
    created() {
        this.searchFetchData();
    },
    methods: {
        creatorChange(val) {
            this.formInline.creator = val
        },
        // 全局获取行数
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        ...mapActions(['ChangePageSize']),
        // 分页
        handleSizeChange(val) {
            this.listQuery.page = 1;
            this.loading = true;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        },
        // 复制
        clipboardSuccessHandler(val) {
            this.$clipboard(val)

            this.$message({
                message: '复制成功！',
                type: 'success'
            });
        },
        clipboardErrorHandler() {
            this.$message.error('复制失败，请手动尝试复制！');
        },
        // 查询列表
        searchFetchData() {
            this.loading = true;
            
            this.formInline.fProvinceId = (this.formInline.fProvinceId === ''|'请选择') ? null : this.formInline.fProvinceId;
            this.formInline.fCityId = (this.formInline.fCityId === ''|'请选择')? null:this.formInline.fCityId;
            this.formInline.fAreaId = (this.formInline.fAreaId === ''|'请选择')? null:this.formInline.fAreaId;
            this.formInline.activityTitle = (this.formInline.activityTitle ==='')? null:this.formInline.activityTitle;
            this.formInline.creator = (this.formInline.creator === '')? null:this.formInline.creator;

            findActivityByPage(this.listQuery.page, this.config.pageSize, this.formInline.fProvinceId, this.formInline.fCityId, this.formInline.fAreaId,
            this.formInline.activityTitle, this.formInline.status, this.formInline.creator).then(response => {
                if (response.data.status==200) {
                    this.dataApply = response.data.content.list;
                    this.listQuery.total = response.data.content.pagination.total;
                    
                    this.loading = false;
                } else {
                    this.$message({
                        type: 'warning',
                        message: response.data.errorMsg
                    })
                }
            });
        },
        // 表单查询
        onSubmit(ruleForm) {
            
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    this.listQuery.page = 1;
                    this.searchFetchData();
                } else {
                    return false;
                }
            });
        },
        // 筛选框选择
        selectable(rows) {
            return rows.status === '0';
        },
        // 批量删除
        deleteRole() {
            if (this.multipleSelection.length<=0) {
                this.$message({
                    type: 'warning',
                    message: '请选择要删除的活动!'
                })
            }
            let roleIds = '';
            for (let i=0;i<this.multipleSelection.length;i++) {
                if (this.multipleSelection[i].status === '0') {
                    roleIds+=this.multipleSelection[i].id+','; 
                }
            }
            roleIds=roleIds.substring(0, roleIds.length-1)
            if (roleIds.length == 0) {
                return;
            } 
            this.$confirm('此操作将批量删除选中活动, 是否继续?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: '' // warning
            }).then(() => {
                getDelete(roleIds).then(response => {
                   
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                });  
            }).catch(e => {       
                console.log(e);
            });
        },
        // 删除
        deleteList(obj) {
            this.deleteActivity(obj.id);
        },
        // 删除功能
        deleteActivity(id) {
            this.$confirm('确定删除活动？', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: ' '// warning
            }).then(() => {
                getDelete(id).then(response => {
                    this.searchFetchData();
                    this.pageQuery.page = 1;
                    this.$message.success(response.data.errorMsg);
                    
                })
            }).catch((e) => {
                this.$message.info('已取消删除');     
            });
                
        },
        // 上下线
        onlineOrDown(row) {
            if (row) {
                if (row.status === '0') {
                    this.$confirm('是否上线?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' '
                    }).then(() => {
                        this.loading = true;
                        onlineOrDown(row.id, row.status).then(data => {
                            this.loading = false;
                            this.searchFetchData();
                            this.$message({
                                type: 'success',
                                message: '上线成功!'
                            });
                        }).catch(Error => {
                            this.loading = false;
                            this.$message.error(Error);
                        })
                    }).catch(() => {
                        this.loading = false;
                        this.$message({
                            type: 'info',
                            message: '已取消上线'
                        });          
                    });
                } else {
                    this.$confirm('是否下线?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' '
                    }).then(() => {
                        this.loading = true;
                        onlineOrDown(row.id, row.status).then(data => {
                            this.loading = false;
                            this.searchFetchData();
                            this.$message({
                                type: 'success',
                                message: '下线成功!'
                            });
                        }).catch(Error => {
                            this.loading = false;
                            this.$message.error(Error);
                        })
                    }).catch(() => {
                        this.loading = false;
                        this.$message({
                            type: 'info',
                            message: '已取消下线'
                        });          
                    });
                }

                // setTimeout(() => {
                //     this.loading = false;
                //     onlineOrDown(row.id, row.status).then(response => {
                //         this.searchFetchData();
                //         this.$message.success(response.data.errorMsg);
                //     });
                // }, 200);
            }
        },
        // 添加活动跳转
        goToaddActivity() {
            this.$router.push('addActivity');
        },
        // 编辑活动跳转
        goToeditActivity(row) {
            this.$router.push({
                path: `editActivity/${row.id}`
            });
        },
        // 查看活动跳转
        goToactivityDetail(row) {
            this.$router.push({
                path: `activityDetail/${row.id}`
            });
        }
    },
    watch: {// 局部刷新列表
        cacheUpdated(val) {
            val && this.searchFetchData();
        }
    }

}
</script>
<style lang="scss" scoped>
.content {
    position: relative;
    padding: 0px;
    $bgcolor:#fff;
    .formInline {
        .formBtn{
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition{
                position: absolute;
                right:0px; 
                top: 18px;
            }
        }
    }
    .btn{
        // padding-left: 5px;
        color: #37a1fb;
        cursor: pointer;
    }
}    
</style>